<template>
  <div class="app-container">
    <el-form
      ref="userInfoForm"
      :model="userInfo"
      label-width="120px"
      class="form-container"
      :rules="userRules"
    >
      <el-form-item label="用户名" prop="username">
        <!-- <el-input v-model="userInfo.username" /> -->
        <div v-text="userInfo.username"></div>
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="userInfo.nickname" />
      </el-form-item>
      <el-form-item label="头像" prop="avatar">
        <el-upload
          action=""
          class="avatar-uploader"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :http-request="customUploadImage"
          :limit="1"
        >
          <img
            v-if="userInfo.avatar.length > 0"
            :src="userInfo.avatar"
            class="avatar"
          />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="userInfo.email" type="email" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="userInfo.phone" />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-radio v-model="userInfo.gender" :label="0">男</el-radio>
        <el-radio v-model="userInfo.gender" :label="1">女</el-radio>
      </el-form-item>
      <el-form-item label="是否启用" prop="status">
        <el-switch v-model="userInfo.status" />
      </el-form-item>
      <el-form-item label="用户类型" prop="type">
        <el-select v-model="userInfo.type" placeholder="请选择用户类型">
          <el-option label="系统用户" value="0"></el-option>
          <el-option label="普通用户" value="1"></el-option>
          <el-option label="管理员用户" value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="userInfo.remark" type="textarea" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmitUser">提交</el-button>
        <!-- <el-button @click="handleCancelUser">重置</el-button> -->
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { updateUser, getUserById } from "@/api/system";
import { fetchOssTokenApi } from "@/api/image";
import OSS from "ali-oss";

export default {
  filters: {
    statusFilter(status) {
      const statusList = ["success", "info"];
      return statusList[status];
    },
    userTypeFilter(type) {
      const userType = ["系统用户", "普通用户", "管理员用户"];
      return userType[type];
    },
  },
  data() {
    return {
      userInfo: {
        username: "",
        password: "",
        nickname: "",
        type: "",
        email: "",
        phone: "",
        gender: 0,
        avatar: "",
        status: true,
        remark: "",
      },
      userRules: {
        username: [
          { required: true, message: "请输入登录用户名", trigger: "blur" },
          { min: 3, message: "长度需要大于3和字符", trigger: "blur" },
        ],
        nickname: [{ required: true, message: "请输入昵称", trigger: "blur" }],
        email: [
          {
            type: "email",
            required: true,
            message: "请输入正确邮箱",
            trigger: "blur",
          },
        ],
        phone: [],
        avatar: [],
        remark: [],
      },
    };
  },
  mounted() {
    const userId = this.$route.query.userId;
    if (userId) {
      getUserById(userId).then((res) => {
        res.data.status = res.data.status === 0;
        this.userInfo = res.data;
        this.userInfo.type = ["系统用户", "普通用户", "管理员用户"][
          this.userInfo.type
        ];
      });
    } else {
      this.$router.back();
    }
  },
  methods: {
    handleSubmitUser() {
      this.$refs["userInfoForm"].validate((valid) => {
        if (valid) {
          let userInfoFrom = Object.assign({}, this.userInfo);
          userInfoFrom.status = this.userInfo.status ? 0 : 1;
          updateUser(userInfoFrom).then((res) => {
            this.$notify.success({
              title: "提示",
              message: res.message,
            });
            setTimeout(() => {
              this.$router.push("/system/user");
            }, 500);
          });
        } else {
          this.$message.warning({
            message: "请完整填写信息",
            showClose: true,
          });
        }
      });
    },
    handleCancelUser() {
      this.userInfo = {
        username: "",
        password: "",
        nickname: "",
        type: "",
        email: "",
        phone: "",
        gender: 0,
        avatar: "",
        status: 0,
        remark: "",
      };
    },
    beforeAvatarUpload(file) {
      const fileType = file.type; //获取文件类型
      const isImage = fileType.indexOf("image") != -1; // 判断是否是图片类型
      if (!isImage) {
        this.$notify.error({
          title: "提示",
          message: "请选择图片类型文件",
        });
        return false;
      }
      return true;
    },
    customUploadImage(e) {
      fetchOssTokenApi().then((res) => {
        const tokenInfo = res.data;
        let client = new OSS({
          region: tokenInfo.region,
          accessKeyId: tokenInfo.accessKeyId,
          accessKeySecret: tokenInfo.accessKeySecret,
          stsToken: tokenInfo.securityToken,
          bucket: tokenInfo.bucket,
        });
        //上传文件
        const fp = e.file;
        // 构造文件名
        const name = fp.name;
        let strs = name.split(".");
        const filename = tokenInfo.uuid + "." + strs[strs.length - 1];
        let curTime = new Date();
        let year = curTime.getFullYear(),
          month = curTime.getMonth() + 1,
          day = curTime.getDate();
        let dir =
          year +
          "/" +
          (month < 10 ? "0" + month : month) +
          "/" +
          (day < 10 ? "0" + day : day) +
          "/";
        client
          .put(dir + filename, fp)
          .then((res) => {
            this.userInfo.avatar = res.url;
            this.$notify.success({
              title: "提示",
              message: "图片上传成功",
            });
          })
          .catch((err) => {
            this.$notify.error({
              title: "提示",
              message: "出现未知错误，图片上传失败",
            });
          });
      });
    },
  },
};
</script>

<style scoped>
.form-container {
  width: 80%;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9 !important;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  object-fit: cover;
  display: block;
}
</style>
